﻿using System.Management;
using Microsoft.ManagementConsole;

namespace Vicos.Management
{
    public class ManagementListView : MmcListView
    {
        private MmcListViewColumn NodeColumn, VirtualMachinesColumn, LoadColumn, ProcRatioColumn, StatusColumn;

        protected override void OnInitialize(AsyncStatus status)
        {
            NodeColumn = new MmcListViewColumn("Node");
            VirtualMachinesColumn = new MmcListViewColumn("Running Virtual Machines");
            LoadColumn = new MmcListViewColumn("Memory Load");
            ProcRatioColumn = new MmcListViewColumn("Processor Ratio");
            StatusColumn = new MmcListViewColumn("Status");

            Columns.AddRange(new MmcListViewColumn[] { VirtualMachinesColumn, ProcRatioColumn });

            this.Refresh();

            // Add a view Action.
            Action ViewAction = new Action("Refresh", "refresh", -1, "Refresh");
            ViewAction.Checked = true;
            ActionsPaneItems.Add(ViewAction);

            base.OnInitialize(status);
        }

        /// <summary>
        /// Handle view global action execution.
        /// </summary>
        protected override void OnAction(Action action, AsyncStatus status)
        {
            string actionString = action.Tag as string;
            if (actionString != null)
            {
                switch (actionString)
                {
                    case "Refresh":
                        {
                            this.Refresh();
                            break;
                        }
                }
            }
        }

        private void Refresh()
        {
            this.ResultNodes.Clear();

            ManagementObjectSearcher s =
                new ManagementObjectSearcher(
                    @"root\directory\ldap",
                    "SELECT ds_name FROM ds_computer WHERE ds_operatingSystem = 'Hyper-V Server'"
                    );

            foreach (ManagementObject item in s.Get())
            {
                ResultNode node = new ResultNode();
                string computer = (string)item.GetPropertyValue("ds_name");
                int vm_count;
                double proc_ratio;

                vm_count = Counters.getVMCount(computer);
                proc_ratio = Counters.getProcessorRatio(computer);

                node.DisplayName = computer;
                node.SubItemDisplayNames.AddRange(new string[]  
                                    {
    						            vm_count != -1 ? vm_count.ToString() : "n/a",
                                        proc_ratio != -1 ? proc_ratio.ToString() : "n/a"
                                    });
                ResultNodes.Add(node);

            }
        }
    }
}
